package com.jiang.gzjp.struts.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.jiang.gzjp.struts.form.UploadForm;

/** 
 * MyEclipse Struts
 * Creation date: 02-28-2019
 * 
 * XDoclet definition:
 * @struts.action path="/upload" name="uploadForm" input="/form/upload.jsp" scope="request" validate="true"
 */
public class UploadAction extends Action {
	/*
	 * Generated Methods
	 */

	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws FileNotFoundException, IOException {
		UploadForm uploadForm = (UploadForm) form;// TODO Auto-generated method stub
		System.out.println("用户名称为:" + uploadForm.getMember().getName());
		FormFile photo = uploadForm.getPhoto();
		System.out.println("文件名称:" + photo.getFileName()+",文件大小:"+photo.getFileSize()+",文件类型:"+photo.getContentType()+",文件数据:"+new String(photo.getFileData()));
		// 实现文件上传
		String fileName = UUID.randomUUID().toString() + photo.getFileName();
		String uploadFilePath = request.getServletContext().getRealPath("/") + fileName ;
		InputStream is = photo.getInputStream();
		OutputStream os = new FileOutputStream(new File(uploadFilePath));
		byte[] bytes = new byte[1024];
		int len = 0;
		while((len = is.read(bytes)) != -1){
			os.write(bytes, 0, len);
		}
		os.flush();
		os.close();
		is.close();
		return null; // 不跳转了
	}
}